<template>
  <div class="dashboard">
    <!-- 数据概览 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="never" class="data-card">
            <template #header>
              <div class="card-header">
                <span>总用户数</span>
                <el-icon><User /></el-icon>
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ statistics.totalUsers }}</div>
              <div class="sub-info">
                <span>新增: <el-tag size="small" type="success">+{{ statistics.newUsers }}</el-tag></span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="never" class="data-card">
            <template #header>
              <div class="card-header">
                <span>课程数量</span>
                <el-icon><Reading /></el-icon>
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ statistics.totalCourses }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="never" class="data-card">
            <template #header>
              <div class="card-header">
                <span>收藏总数</span>
                <el-icon><Star /></el-icon>
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ statistics.totalFavorites }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="never" class="data-card">
            <template #header>
              <div class="card-header">
                <span>浏览总数</span>
                <el-icon><View /></el-icon>
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ statistics.totalViews }}</div>
              <div class="sub-info">
                <span>活跃用户: <el-tag size="small" type="primary">{{ statistics.activeUsers }}</el-tag></span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <!-- 浏览量排行柱状图 -->
        <el-col :span="12">
          <el-card shadow="never" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>课程浏览量排行</span>
              </div>
            </template>
            <div ref="viewsRankingChart" style="height: 300px"></div>
          </el-card>
        </el-col>
        
        <!-- 课程难度分布 -->
        <el-col :span="12">
          <el-card shadow="never" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>收藏课程难度分布</span>
              </div>
            </template>
            <div ref="difficultyChart" style="height: 300px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 热门课程和收藏趋势 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <!-- 收藏趋势 -->
        <el-col :span="12">
          <el-card shadow="never" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>近30天收藏趋势</span>
              </div>
            </template>
            <div ref="favoriteTrendChart" style="height: 300px"></div>
          </el-card>
        </el-col>
        
        <!-- 最受欢迎课程 -->
        <el-col :span="12">
          <el-card shadow="never" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>最受欢迎课程</span>
              </div>
            </template>
            <div v-loading="loading" class="popular-courses">
              <el-table :data="popularCourses" style="width: 100%" :max-height="250">
                <el-table-column prop="title" label="课程名称" min-width="180" show-overflow-tooltip />
                <el-table-column prop="institution" label="机构" width="120" show-overflow-tooltip />
                <el-table-column prop="difficulty" label="难度" width="80">
                  <template #default="{ row }">
                    <el-tag :type="getDifficultyType(row.difficulty)">{{ row.difficulty }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="favoriteCount" label="收藏数" width="80" sortable />
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { User, Star, Reading, ChatLineSquare, View } from '@element-plus/icons-vue'
import request from '@/utils/request'
import * as echarts from 'echarts'

const API_BASE_URL = process.env.VUE_APP_BASE_API || '/api'
const router = useRouter()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const loading = ref(false)
const avgRating = ref(0)

// 统计数据
const statistics = ref({
  totalUsers: 0,
  totalCourses: 0,
  totalFavorites: 0,
  totalReviews: 0,
  totalViews: 0,
  newUsers: 0,
  activeUsers: 0
})

// 收藏统计数据
const favoriteStats = ref({
  totalFavorites: 0,
  favoriteTrend: [],
  mostFavoritedCourses: [],
  difficultyDistribution: []
})

// 浏览统计数据
const viewsStats = ref({
  topViewedCourses: []
})

// 最受欢迎课程
const popularCourses = ref([])

// 图表引用
const difficultyChart = ref(null)
const favoriteTrendChart = ref(null)
const viewsRankingChart = ref(null)
let difficultyChartInstance = null
let favoriteTrendChartInstance = null
let viewsRankingChartInstance = null

// 格式化头像URL，确保包含API前缀
const formatAvatarUrl = (url) => {
  if (!url) return ''
  
  // 如果已经是完整URL(包含http或https)，则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果已经包含API前缀，则直接返回
  if (url.startsWith(API_BASE_URL)) {
    return url
  }
  
  // 否则添加API前缀
  return `${API_BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
}

// 获取系统概览数据
const fetchSystemOverview = async () => {
  try {
    loading.value = true
    const res = await request.get('/statistics/overview', null, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        statistics.value = data
      }
    })
  } catch (error) {
    console.error('获取系统概览数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取收藏统计数据
const fetchFavoriteStats = async () => {
  try {
    loading.value = true
    await request.get('/statistics/favorite-stats', { limit: 10 }, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        favoriteStats.value = data
        popularCourses.value = data.mostFavoritedCourses || []
        
        // 初始化收藏统计图表
        initDifficultyChart(data.difficultyDistribution || [])
        initFavoriteTrendChart(data.favoriteTrend || [])
      }
    })
  } catch (error) {
    console.error('获取收藏统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取浏览统计数据
const fetchViewsStats = async () => {
  try {
    loading.value = true
    await request.get('/statistics/course-views-ranking', { limit: 10 }, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        viewsStats.value.topViewedCourses = data || []
        
        // 初始化浏览量排行图表
        initViewsRankingChart(data || [])
      }
    })
  } catch (error) {
    console.error('获取浏览统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化浏览量排行图表
const initViewsRankingChart = (data) => {
  if (!viewsRankingChartInstance) return
  
  // 提取课程标题和浏览量数据
  const courses = data.slice(0, 10).map(item => item.title)
  const viewCounts = data.slice(0, 10).map(item => item.viewCount)
  
  // 反转数组，让最高的显示在顶部
  courses.reverse()
  viewCounts.reverse()
  
  viewsRankingChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 次浏览'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '浏览次数',
      nameTextStyle: {
        align: 'right',
        padding: [0, 10, 0, 0]
      }
    },
    yAxis: {
      type: 'category',
      data: courses,
      axisLabel: {
        width: 120,
        overflow: 'truncate'
      }
    },
    series: [
      {
        name: '浏览量',
        type: 'bar',
        data: viewCounts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        }
      }
    ]
  })
}

// 初始化难度分布图表
const initDifficultyChart = (data) => {
  if (!difficultyChartInstance) return
  
  // 根据难度设置颜色
  const difficultyColors = {
    '初级': '#67C23A',
    '中级': '#409EFF',
    '高级': '#E6A23C',
    '专家': '#F56C6C'
  }
  
  difficultyChartInstance.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      padding: [20, 0, 0, 0]
    },
    series: [{
      name: '难度分布',
      type: 'pie',
      radius: '65%',
      center: ['55%', '50%'],
      itemStyle: {
        borderRadius: 6,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}\n{c}个',
        fontSize: 14,
        fontWeight: 'bold'
      },
      labelLine: {
        smooth: true,
        length: 10,
        length2: 10
      },
      emphasis: {
        label: {
          fontSize: 16,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      data: data.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: {
          color: difficultyColors[item.name] || null
        }
      }))
    }]
  })
}

// 初始化收藏趋势图表
const initFavoriteTrendChart = (data) => {
  if (!favoriteTrendChartInstance) return
  
  // 日期和收藏数量
  const dates = data.map(item => item.date)
  const counts = data.map(item => item.count)
  
  favoriteTrendChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        interval: 'auto',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '收藏数',
      minInterval: 1
    },
    series: [{
      name: '收藏数',
      type: 'bar',
      data: counts,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      }
    }]
  })
}

// 根据难度获取对应的标签类型
const getDifficultyType = (difficulty) => {
  const typeMap = {
    '初级': 'success',
    '中级': 'primary',
    '高级': 'warning',
    '专家': 'danger'
  }
  return typeMap[difficulty] || 'info'
}

// 角色标签
const roleLabel = computed(() => {
  const roleMap = {
    'ADMIN': '系统管理员',
    'USER': '普通用户'
  }
  return roleMap[userInfo.value?.role] || '未知角色'
})

// 初始化图表
const initCharts = () => {
  if (difficultyChart.value) {
    difficultyChartInstance = echarts.init(difficultyChart.value)
  }
  if (favoriteTrendChart.value) {
    favoriteTrendChartInstance = echarts.init(favoriteTrendChart.value)
  }
  if (viewsRankingChart.value) {
    viewsRankingChartInstance = echarts.init(viewsRankingChart.value)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  difficultyChartInstance?.resize()
  favoriteTrendChartInstance?.resize()
  viewsRankingChartInstance?.resize()
}

onMounted(() => {
  // 初始化图表并获取数据
  initCharts()
  fetchSystemOverview()
  fetchFavoriteStats()
  fetchViewsStats()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理图表实例和事件监听
  if (difficultyChartInstance) {
    difficultyChartInstance.dispose()
  }
  if (favoriteTrendChartInstance) {
    favoriteTrendChartInstance.dispose()
  }
  if (viewsRankingChartInstance) {
    viewsRankingChartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;

  .data-overview {
    margin-bottom: 24px;

    .data-card {
      height: 100%;
      min-height: 180px;
      background: #ffffff;
      // border-radius: 0;
      border: 1px solid #ebeef5;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;

        span {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }

        .el-icon {
          font-size: 24px;
          color: #909399;
        }
      }

      .card-content {
        text-align: center;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 24px;
        
        .number {
          font-size: 36px;
          font-weight: 700;
          margin: 10px 0;
          color: #303133;
        }
        
        .sub-info {
          font-size: 14px;
          color: #606266;
          margin-top: 8px;
          
          .el-tag {
            margin-left: 8px;
            padding: 4px 8px;
            border-radius: 12px;
            font-weight: 500;
          }
        }
      }
    }
  }

  .chart-section {
    margin-bottom: 24px;

    .chart-card {
      height: 100%;
      min-height: 400px;
      background: #ffffff;
      border-radius: 0;
      border: 1px solid #ebeef5;
      display: flex;
      flex-direction: column;
      
      .card-header {
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;
        
        span {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .popular-courses {
        padding: 16px;
        flex-grow: 1;
        
        .el-table {
          background: transparent;
          
          &::before {
            display: none;
          }
          
          th {
            background: #f5f7fa;
            font-weight: 600;
            color: #303133;
          }
          
          td {
            padding: 12px 0;
          }
          
          .el-tag {
            border-radius: 12px;
            padding: 4px 12px;
            font-weight: 500;
          }
        }
      }
      
      .el-card__body {
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        padding: 0;
      }
    }
  }
  
  .el-row {
    margin: 0 -12px;
    
    .el-col {
      padding: 0 12px;
      margin-bottom: 24px;
    }
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .dashboard {
    padding: 12px;
    
    .data-card {
      min-height: 160px;
      
      .card-content .number {
        font-size: 28px;
      }
    }
    
    .chart-card {
      min-height: 350px;
    }
  }
}
</style> 